<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\Wxapp;
use think\Cache;
use \think\Db;
use \think\Request;
use \think\Log;

/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;
        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }
	
	public function login22()
	{
	    $model = new UserModel;
		$resArr = $model->login22($this->request->post());
		// mmmodify 用微信昵称加用户id号入库，此处包含判断有问题
		// if(!stristr($resArr['nickName'], '_')){
		// 	$newNickName = $resArr['nickName'].'_'.$resArr['user_id'];
		// 	$res = Db::name('user')->where('user_id',$resArr['user_id'])->update(['nickName'=>$newNickName]);
		// }
	    return $this->renderSuccess([
	        'user_id' => $resArr['user_id'],
			'nickName' => $resArr['nickName'],
			'avatarUrl' => $resArr['avatarUrl'],
			'true_mobile' => $resArr['true_mobile'],
			'user_openid' => $resArr['user_openid'],
	        'token' => $model->getToken()
	    ]);
	}
	
	// 获取微信的手机号码 mmmodify
	public function getwxMobile(){
		$model = new UserModel;
		$inArr = $this->request->post();
		if($inArr['user_id']>0){
			$resArr = $model->getwxMobile($inArr);
			// 将获取到的手机号入库
			$true_mobile = $resArr['true_mobile'];
			if($true_mobile != ''){
				$res = Db::name('user')->where('user_id',$inArr['user_id'])->update(['true_mobile'=>$true_mobile]);
			}
            else{
                // 删除accesstoken，使其可以重新获取
                $wxConfig = Wxapp::getWxappCache();
                $appid = $wxConfig['app_id'];
                $cacheKey = $appid . '@access_token';
                Cache::clear($cacheKey);
                Cache::rm($cacheKey);
                return $this->renderError('手机号码获取失败');
            }
            // 1. 获取了电话后，判断一下是否进线，如果进线，并且dl_userid为0，则修改dl_userid
            // 2. 如果没进线，判断是否存在父级，并且父级为地推人员，寻找地推人员最近一次的所在的机构shop_id和活动act_id，进线入库
            $this->opmZfInline($inArr['user_id'], $true_mobile);
			return $this->renderSuccess([
				'true_mobile' => $true_mobile
			]);
		}
		else{
			return $this->renderError('未找到用户ID，请重新进入小程序');
		}
	}
    /** 处理转发后获取电话号码的进线功能 目前是必需存在上级才开启进线*/
    public function opmZfInline($u_id, $mobile){
        // 1. 查找该手机号是否在进线表中存在手动添加，如果存在，则直接修改
        $shouAddObj = Db::name('ditui_user')->where(['du_mobile'=>$mobile, 'dl_userid'=>0])->select()->toArray();
        // 因为存在toArray，所以注意如下的判断
        if(count($shouAddObj) > 0){
            $dlArr = array();
            foreach ($shouAddObj as $vvv){
                $dlArr[] = $vvv['dl_id'];
            }
            $dlStr = implode(',', $dlArr);
            $sss = "update ".getTable('ditui_user')." set dl_userid=$u_id , dl_addtime='".date('Y-m-d H:i:s',time())."' where dl_id in ($dlStr)";
            //Log::write('这是一条测试日志'.$sss, 'info');
            //ddd($sss);
            Db::query($sss);
        }
        // 2. 查找用户的上级，查找上级是否是地推专员，找到最后一次的服务的shopid
        else{
            $refObj = Db::name('dealer_referee')->where(['user_id'=>$u_id, 'level'=>1])->find();
            if($refObj){
                $fatherId = $refObj['dealer_id'];
                $dituiSellerObj = Db::name('ditui_seller')->where(['ds_userid'=>$fatherId])->order(['ds_id' => 'desc'])->find();
                if($dituiSellerObj){
                    $shopId = $dituiSellerObj['ds_shopid'];
                    // 查找此时是否已经进线到地推专员最后一次服务的机构中
                    $inlineObj = Db::name('ditui_user')->where(['dl_userid'=>$u_id, 'dl_shopid'=>$shopId])->order(['dl_id' => 'desc'])->find();
                    if($inlineObj){
                        // 如果进线，并且还没有绑定微信用户，则直接绑定微信用户
                        if($inlineObj['dl_userid']==0){
                            $upArr000['dl_userid'] = $u_id;
                            $upArr000['dl_addtime'] = date('Y-m-d H:i:s',time());
                            Db::name('ditui_user')->where('dl_id',$inlineObj['dl_id'])->update($upArr000);
                        }
                    }
                    // 用户进线，转发的不给积分奖励，避免地推专员刷业绩薅羊毛
                    else{
                        $inArr['dl_activeid'] = 0;  //纯转发而来
                        $inArr['dl_activetitle'] = $dituiSellerObj['ds_truename']."(".$dituiSellerObj['ds_mobile'].")转发进线";
                        $inArr['dl_shopid'] = $shopId;
                        $inArr['dl_shopname'] = $dituiSellerObj['ds_shopname'];
                        $inArr['dl_dituiuid'] = $dituiSellerObj['ds_userid'];
                        $inArr['dl_dituiname'] = $dituiSellerObj['ds_truename'];
                        $inArr['dl_dituimobile'] = $dituiSellerObj['ds_mobile'];
                        $inArr['dl_allfen'] = 0;
                        $inArr['dl_dituifen'] = 0;
                        $inArr['dl_kehufen'] = 0;
                        $inArr['dl_userid'] = $u_id;
                        $inArr['du_mobile'] = $mobile;
                        // dl_send_qaid可以看成是类型，0：代表光领取积分的类型，1：代表答题后领积分的类型
                        $inArr['dl_send_qaid'] = 0;
                        $inArr['dl_addtime'] = date('Y-m-d H:i:s',time());
                        Db::name('ditui_user')->insert($inArr);
                    }
                }
            }
        }
    }
	// 单纯地头像上传
	public function headerImgUpload(){
		$file = $this->request->file('headerImgUploadFiles');
		$inArr  = $this->request->post();
		if($inArr['user_id']>0){
			$imgName = "header_".$inArr['user_id'];
			if($file){
				$imgPath = ROOT_PATH. DS .'../web'. DS. 'uploads' . DS . 'headerimg';
				$info = $file->validate(['size'=>15678,'ext'=>'jpg,jpeg,png,gif'])->move($imgPath,$imgName);
				// halt($info);
				if($info){
					// 成功上传后 获取上传信息
					// 输出 jpg
					$backArr['type'] = $info->getExtension();
					// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
					$backArr['saveName'] = $info->getSaveName();
					// 输出 42a79759f284b767dfcb2a0197904287.jpg
					$backArr['fileName'] = $info->getFilename();
					$backArr['dbPath'] = '/uploads/headerimg/'.$backArr['saveName'];
					return $this->renderSuccess($backArr);
				}else{
					// 上传失败获取错误信息
					return $this->renderError('头像超过1.5M或格式不对');
				}
			}
		}
		else{
			return $this->renderError('未找到用户ID，请重新进入小程序');
		}
		 
	}
	// 包含用户头像的微信用户注册
	public function headerReg(){
		$model = new UserModel;
		$inArr  = $this->request->post();
		if($inArr['user_id']>0){
			if($inArr['isUploadImg']=='yes'){
				// 将头像和昵称真实姓名入库，然后登录login33，生成token
				$arr['avatarUrl'] = $inArr['dbImgPath'];
				$arr['nickName'] = $inArr['nickName'];
				$arr['true_name'] = $inArr['trueName'];
                $arr['gift_code'] = rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9);
                $arr['user_birthstr'] = date('Y-m-d', strtotime($inArr['birthStr']));
				$res = Db::name('user')->where('user_id',$inArr['user_id'])->update($arr);
			}
			
			// 小程序获取头像之后，第二次通过openid计算token然后入库，每次进入小程序的时候，已做静默登录并缓存token ，此次主要因为$model->getToken要使用
			$model->login33($inArr);
			
			$backArr['token'] = $model->getToken();
			$backArr['user_id'] = $inArr['user_id'];
			
			return $this->renderSuccess($backArr);
		}
		else{
			return $this->renderError('未找到用户ID，请重新进入小程序');
		}
	}
	
	//用户实时发送经纬度，修改技师当前实时位置
	public function changeSkillManState($skillgoodid,$lng,$lat){
		$backArr['aaa'] = $skillgoodid;
		$backArr['bbb'] = 456;
		// $mmSkillMan = new SkillManGoodModel;
		// $backArr['ccc'] = $mmSkillMan->test(789);
		// $res = Db::name('goods')->select()->toArray();
		$res = Db::name('goods')->where('goods_id',$skillgoodid)->update(['goods_lng'=>$lng, 'goods_lat'=>$lat]);
		$backArr['ccc'] = $res;
		return $this->renderSuccess($backArr);
	}
	
	//技师设置为可正常接单状态
	public function setGookJDok($skillgoodid,$userid){
		if($skillgoodid==0 || $userid==0){
			return $this->renderError('参数错误');
		}
		else{
			// 先判断该技师有没有已支付的订单，正在进行中的订单
			$sql = "select aa.goods_id,bb.pay_status,bb.order_status from zj_order_goods aa left join zj_order bb on aa.order_id=bb.order_id 
			where aa.goods_id=$skillgoodid and bb.pay_status=20 and bb.order_status=10";
			$data = Db::query($sql);
			if(count($data)>0){
				return $this->renderError('您有进行中的订单，或已被客户预约，无法设置正常接单');
			}
			else{
				// 设置商品的sku规格全部数量为1，设置商品的serve_state字段
				$res = Db::name('goods')->where('goods_id',$skillgoodid)->update(['serve_state'=>1]);
				// $res22 = Db::name('goods_sku')->where('goods_id',$skillgoodid)->update(['stock_num'=>1]);
				$backArr['aa'] = $res;
				// $backArr['bb'] = $res22;
				return $this->renderSuccess($backArr);
			}
		}
	}

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }
    // 获取nav
        public function getnav()
    {
        $wxapp_id= input('wxapp_id');
        // 图片上传方式
        $storage = Db::name('setting')->where(['key'=>'storage','wxapp_id'=>$wxapp_id])->find();
        $va = $storage['values'];
        $bdurl= json_decode($va, true); 
        $request = Request::instance();
        $url =$request->domain();//当前站点url
       	$res = Db::name('wxapp_nav')
         ->alias('m')
         ->join('upload_file n','m.logo=n.file_id')
          ->join('upload_file l','m.logo2=l.file_id')
         ->field('m.title_color,m.title_color2,m.title,m.url,m.item,n.file_name as logo,l.file_name as logo2,n.file_url as logourl,l.file_url as logo2url')
       	 ->where(['m.wxapp_id'=>$wxapp_id,'m.state' => 1])
       	 ->order('m.num asc')
       	 ->select()->toArray();
       	 //本地存储
       	 if($bdurl['default']=="local"){
       	 
       	 foreach ($res as $k=>$v){
       	     $res[$k]['logo2']= $url."/uploads/".$v['logo2'];
       	     $res[$k]['logo']= $url."/uploads/".$v['logo'];
       	 }
       	     
       	 }
       	 //非本地存储
      else {
        
    
       	 
       	 foreach ($res as $k=>$v){
       	     $res[$k]['logo2']= $v['logo2url']."/".$v['logo2'];
       	     $res[$k]['logo']= $v['logourl']."/".$v['logo'];
       	 }
       	     
       	 }
        return $this->renderSuccess(compact('res'));
    }
      // 获取地址
        public function geturl()
    {
        $wxapp_id= input('wxapp_id');
        // 当前用户信息  
    
    
        return $this->renderSuccess([
            'url' => "https://api.wxboo.cn/attachment/"
        ]);
    }

}
